<template>
  <k-form-modal
    v-model="state.visible"
    drawer
    width="640px"
    :loading="state.loading"
    title="推广链接发放"
    label-width="90px"
    :model="state.model"
    :rules="state.rules"
    @submit="methods.onSubmit"
    @cancel="methods.onCancel"
  >
    <el-form-item label="选择讲师" prop="agent_id">
      <el-select v-model="state.model.agent_id" :loading="agentLoading" disabled placeholder="不限" filterable style="width: 300px">
        <el-option v-for="item in agentOptions" :key="item.agent_id" :label="item.name" :value="item.agent_id" />
      </el-select>
    </el-form-item>
    <el-form-item label="会员版本" prop="vip_level">{{ maps.optionsPromoteLinkVipLevels[state.model.vip_level] }}</el-form-item>
    <el-form-item label="兑换时长" prop="vip_type">
      {{ state.model.vip_type }}
    </el-form-item>
    <el-form-item label="渠道选择" prop="channel">
      {{ state.model.channel }}
    </el-form-item>
    <el-form-item label="失效时间" prop="invalid_time">
      <el-date-picker v-model="state.model.invalid_time" type="datetime" value-format="X" placeholder="请选择失效时间" style="width: 300px" />
    </el-form-item>
  </k-form-modal>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useFormModal } from '@crud/index';
import { ElMessage } from 'element-plus';
import { maps } from '@/config/index';
import { updateLecPromoteLink, getLecList } from '@/api/crm-agency/kgj/lecturer';
import { channelMap } from '../hooks/use-table';
defineOptions({
  name: 'KgjPromoteEditModal'
});
const emits = defineEmits(['success']);

// 讲师列表
const agentOptions = ref<any[]>([]);
const agentLoading = ref(false);
const getLecOptions = async () => {
  agentLoading.value = true;
  const res = await getLecList({ data: {}, params: { page: 1, limit: 10000 } });
  agentLoading.value = false;
  agentOptions.value = res?.data?.items ?? [];
};
getLecOptions();
const rowData = ref({});
const { state, ...methods } = useFormModal({
  model: {
  },
  rules: {
    invalid_time: [{ required: true, message: '请选择失效时间' }]
  },
  onShow: (mode = 0, data: any) => {
    rowData.value = {};
    if (data) {
      rowData.value = data;
      state.model = {
        // ...state.model,
        agent_id: data.agent_id,
        extend_id: data.extend_id,
        invalid_time: data.invalid_time,
        vip_level: data.vip_level,
        channel: channelMap[data.channel],
        vip_type: data.vip_type
      };
    }
  },
  onSubmit: async (model: any, mode = 0) => {
    if (mode === 1) {
      const { extend_id, invalid_time } = model;
      const data = {
        extend_id,
        invalid_time: Number(invalid_time)
      };
      const res = await updateLecPromoteLink({ data });
      if (!res.err) {
        ElMessage.success('操作成功');
        emits('success');
      }
      return res;
    }
  }
});
defineExpose({
  show: methods.show
});
</script>
